import { defineStore } from "pinia";
import { getDicData } from "@/api/modules/system";

interface CacheMap {
  [key: string]: [(data: any[]) => void, (error: any) => void][];
}

const cacheMap: CacheMap = {};

export const useSelectStore = defineStore("select", {
  state: () => {
    return {
      dicData: {} as Record<string, any[]>
    };
  },
  actions: {
    setDic(key: string, list: any[]) {
      this.dicData[key] = list;
    },
    getDic(key: string): Promise<any[]> {
      if (this.dicData[key] && this.dicData[key].length > 0) {
        return Promise.resolve(this.dicData[key]);
      } else {
        // if ((cacheMap[key]?.length ?? 0) == 0) {
        cacheMap[key] = [];
        getDicData(key).then(res => {
          const data = res.data as unknown as any[];
          // 使用类型断言将 res.data 断言为 any[] 类型
          while (cacheMap[key].length) {
            const list = data.map(item => ({
              value: item.value,
              label: item.description
            }));
            this.setDic(key, list);
            const [resolve] = cacheMap[key].shift()!;
            resolve(list);
          }
        });
        // }
        return new Promise((resolve, reject) => {
          cacheMap[key].push([resolve, reject]);
        });
      }
    }
  }
});
